I rewrote your code in another way that is more clear to me, maybe others would find this useful. This opens a window in which, the start button initiates the override RF keys state and also there is a stop button:
import AppKit
from vanilla import *
_ignore = {'⌘s', '⇧⌘s', '⌘q', '⇧⌘q'}
MODIFIER_INT_TO_STR = {
AppKit.NSCommandKeyMask: '⌘',
AppKit.NSControlKeyMask: '⌃',
AppKit.NSAlternateKeyMask: '⌥',
AppKit.NSShiftKeyMask: '⇧',
AppKit.NSCommandKeyMask | AppKit.NSShiftKeyMask: '⇧⌘',
AppKit.NSCommandKeyMask | AppKit.NSAlternateKeyMask: '⌘⌥',
AppKit.NSCommandKeyMask | AppKit.NSControlKeyMask : '⌃⌘',
AppKit.NSControlKeyMask | AppKit.NSShiftKeyMask: '⇧⌃',
AppKit.NSAlternateKeyMask | AppKit.NSShiftKeyMask: '⇧⌥',
}
class KeyEventMonitor(object):
def __init__(self):
self.monitor = None
self.w = Window((300, 90), "KeyEventMonitor Debuggin window")
self.w.b1 = Button((10, 10, -10, 20), "Stop",
callback=self.stop)
self.w.b2 = Button((10, 40, -10, 20), "Start",
callback=self.start)
self.w.bind("close", self.stop)
self.w.open()
def stop(self, sender):
self._stopOverridingRFkeys()
def start(self, sender):
self._startOverridingRFkeys()
def _startOverridingRFkeys(self):
self._stopOverridingRFkeys()
self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(
AppKit.NSKeyDownMask, self._keyDown)
def _stopOverridingRFkeys(self):
if self.monitor is not None:
AppKit.NSEvent.removeMonitor_(self.monitor)
self.monitor = None
def _keyDown(self, event):
allKeys = MODIFIER_TO_STR.get(event.modifierFlags(), '') + event.charactersIgnoringModifiers().lower()
if allKeys in _ignore:
print("overriding %s" %allKeys)
else:
self._stopOverridingRFkeys()
AppKit.NSApp().sendEvent_(event)
self._startOverridingRFkeys()
KeyEventMonitor()